import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Result } from '../common/result.interface';
import { LoginUser } from './login/login-user';
import { map } from 'rxjs/operators';
import { of } from 'rxjs';

export interface User {
  id: number;
  name: string;
}



@Injectable({
  providedIn: 'root'
})
export class UserService {

  public user: User

  constructor(private http: HttpClient) { }

  login(user: LoginUser) {
    return this.http.post<Result<User>>('/api/login', user).pipe(
      map((r: Result<User>) => {
        if (r.success) {

          this.user = r.data;
        }

        return r.success;
      })
    );
  }

  validatePhone(tel) {
    return this.http.get(`/api/validate-phone`, {
      params: {
        tel
      }
    });
  }

  isLogin() {
    let token = localStorage.getItem('token');
    return of(!!token);

  }

  getList() {
    return this.http.get('/api/list').pipe(
      map((r: Result<string>) => {
        if (r.success) {
          return r.data;
        }
      })
    );
  }
}
